import riverL1 from "../../geojson/南欧江1-2级河段4326.json"
import "./bubbleDiv.css"
const circleOut = require('./circleRotatationOut.png');
const circleInside = require('./circleRotatationInside.png');
const sectionPoint = [
    [102.4494795, 20.388575],
    [102.4424523, 20.3833288],
    [102.4393346, 20.3765425],
    [102.4324885, 20.3705378],
    [102.4262705, 20.3553242],
    [102.4273145, 20.3368632],
    [102.4307232, 20.330138],
    [102.435591, 20.3112115],
    [102.4258432, 20.3008244],
    [102.4256547, 20.3007359],
    [102.4231051, 20.2902671],
    [102.4072648, 20.2827961],
    [102.3797301, 20.2656641],
    [102.3654946, 20.2514363],
    [102.3385427, 20.234497],
    [102.3347502, 20.2139741],
    [102.3247505, 20.1894902],
    [102.3163084, 20.1633176],
    [102.3174021, 20.1491227]
]
const RiverPlayer = function(viewer, Cesium) {
    var self = this
    this.viewer = viewer
    this.Cesium = Cesium
    this.Cts3Arrays = []
        //断面中心点cts3
    this.sectionCts3Arrays = []
    this.startSection = null
    this.TmpCts3Arrays = []
    this.currentCts3Arrays = []
    this.css3Render = new Css3Renderer(viewer, false, Cesium)
}
RiverPlayer.prototype = {
    drawRiver() {
        try {
            let self = this
            let latlonArray = this.arrayFlat(riverL1.features[0].geometry.coordinates)
            self.Cts3Arrays = this._getPowerLinePosition(latlonArray, false)
                // let sectionlatlonArray = this.arrayFlat(sectionPoint)
            self.sectionCts3Arrays = sectionPoint.concat()
            self.startSection = self.sectionCts3Arrays.shift()
            let polylineEntity = new this.Cesium.Entity({
                id: "riverID",
                polyline: {
                    positions: //Cts3Arrays,
                        new this.Cesium.CallbackProperty(function() {
                        return self.currentCts3Arrays
                    }, false),
                    clampToGround: true,
                    width: 8,
                    // classificationType: this.Cesium.ClassificationType.BOTH
                }
            })
            this.viewer.entities.add(polylineEntity)
            setTimeout(function() {
                self.play()
            }, 9000)

            // this.viewer.flyTo(polylineEntity)
        } catch (err) {

        }
    },
    play() {
        let self = this
            //清除工作要做好，清除之前播放的
        this.TmpCts3Arrays = this.getInsetPoints(this.Cts3Arrays, 100)
        if (self.playInterval) {
            window.clearInterval(self.playInterval)
        }
        self.playInterval = setInterval(function() {
            let newpoi = self.TmpCts3Arrays.shift()
            if (newpoi) {
                var heading = self.Cesium.Math.toRadians(0.0);
                var pitch = self.Cesium.Math.toRadians(-30.0);
                var range = 15000.0;
                //视角跟随
                self.viewer.camera.lookAt(newpoi, new self.Cesium.HeadingPitchRange(heading, pitch, range));
                //慢慢延长河流线
                self.currentCts3Arrays.push(newpoi)
                self.showSectionInfo(newpoi)
            } else {
                self.viewer.camera.lookAtTransform(self.Cesium.Matrix4.IDENTITY);
                window.clearInterval(self.playInterval)
            }
        }, 100)
    },
    //展示断点信息
    showSectionInfo(newpoi) {
        let sectioncts = this.Cesium.Cartesian3.fromDegrees(this.startSection[0], this.startSection[1], 0)
        var disCoumt = this.Cesium.Cartesian3.distance(newpoi, sectioncts)
        let entityId = this.guid()
        if (disCoumt < 150) {

            let element = `<div class='bubbleLayer bubbleLayer-box' id='${entityId}'>
      <!--<div class='line'></div>-->
      <div class='main'>
          <div class="watershedArea">断面<span></span></div>
  <!--                              <div class="regionPercentage">水位:312m<span></span></div>-->
      </div>
  </div>`
                // var cartographic = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(this.startSection);
                // var lat = this.Cesium.Math.toDegrees(cartographic.latitude);
                // var lon = this.Cesium.Math.toDegrees(cartographic.longitude);
            let entityLayer = {
                id: entityId,
                position: [this.startSection[0], this.startSection[1], 0], //高度为 boxHeightMax
                element: element,
                offset: [-110, -155],
                boxHeight: 20000, //中间立方体的高度
                boxHeightDif: 500, //中间立方体的高度增长差值，越大增长越快
                boxHeightMax: 40000, //中间立方体的最大高度
                boxSide: 10000, //立方体的边长
                boxMaterial: this.Cesium.Color.DEEPSKYBLUE.withAlpha(0.5),
                circleSize: 30000, //大圆的大小，小圆的大小默认为一半
                circleInsideImage: circleInside,
                circleOutImage: circleOut
            };
            this.startSection = this.sectionCts3Arrays.shift()
            this.css3Render.append(entityLayer);
        }

    },
    //插值获取平滑路线
    getInsetPoints(points, minDis) {
        var result = []
            //判断两点的距离
        for (var i = 0; i < points.length - 1; i++) {
            var disCoumt = this.Cesium.Cartesian3.distance(points[i], points[i + 1])
            let count = disCoumt / minDis
            if (count > 0) {
                for (var j = 0; j < count; ++j) {
                    var offset = j / count;
                    let insdtPoi = this.Cesium.Cartesian3.lerp(
                        points[i],
                        points[i + 1],
                        offset,
                        new this.Cesium.Cartesian3()
                    );
                    result.push(insdtPoi)
                }
            } else {
                result.push(points[i + 1])
            }

        }

        return result
    },
    _getPowerLinePosition(positions, isHeight) {
        try {
            if (isHeight) {
                return this.Cesium.Cartesian3.fromDegreesArrayHeights(positions)
            } else {
                return this.Cesium.Cartesian3.fromDegreesArray(positions)
            }
        } catch (e) {
            return [];
        }

    },
    /**
     * 二维数组变一维数组
     * @param positions
     * @returns {*}
     */
    arrayFlat(positions) {
        try {
            let pos = positions.flat();
            return pos;
        } catch (e) {

        }
    },
    guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

}
const Css3Renderer = function(myviewer, isBackHide, myCesium) {
    let viewer = myviewer;
    let Cesium = myCesium;
    const scratch = new Cesium.Cartesian2();
    const scene = viewer.scene;
    const camera = viewer.camera;
    const that = this;
    that.container = null;
    that.elements = [];
    that.isBackHide = isBackHide;
    this.__proto__.init = function() {
        let container = document.createElement('div')
        container.className = `znyContainer`
        document.body.appendChild(container)
        that.container = container;
        that.elements.forEach(e => {
            container.insertAdjacentHTML('beforeend', e.element);
        });
        scene.preRender.addEventListener(function() {
            for (let i = 0; i < container.children.length; i++) {
                const p = Cesium.Cartesian3.fromDegrees(that.elements[i].position[0], that.elements[i].position[1], that.elements[i].position[2] || 0)
                const canvasPosition = scene.cartesianToCanvasCoordinates(p, scratch)
                if (Cesium.defined(canvasPosition)) {
                    container.children[i].style.left = parseFloat(canvasPosition.x) + parseFloat(that.elements[i].offset[0]) + 'px'
                    container.children[i].style.top = parseFloat(canvasPosition.y) + parseFloat(that.elements[i].offset[1]) + 'px'
                    if (that.isBackHide) {
                        let j = camera.position,
                            n = scene.globe.ellipsoid.cartesianToCartographic(j).height;
                        if (!(n += 1 * scene.globe.ellipsoid.maximumRadius, Cesium.Cartesian3.distance(j, p) > n)) {
                            container.children[i].style.display = 'block'
                        } else {
                            container.children[i].style.display = 'none'
                        }
                    }
                }
            }
        })
    };
    this.__proto__.clearAll = function(id) {
        that.elements = []
        that.container.innerHTML = ''
    };
    this.__proto__.remove = function(id) {
        that.elements = that.elements.filter(e => e.id !== id)
        if (document.getElementById(id)) {
            let dom = document.getElementById(id);
            if (dom) {
                that.container.removeChild(document.getElementById(id))
            }
        }
    };
    this.__proto__.append = function(object) {
        that.elements.push(object);
        that.container.insertAdjacentHTML('beforeend', object.element)
    };


    this.init()
}
export { RiverPlayer, Css3Renderer }